package com.ch.light.web.service.impl;

import com.ch.light.mybatis.ParamFilter;
import com.ch.light.web.mapper.AppVersionMapper;
import com.ch.light.web.model.AppVersion;
import com.ch.light.web.service.AppVersionService;
import com.ch.utils.CommonUtils;
import com.ch.utils.UUIDGenerator;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * 描述：com.ch.light.web.service.impl
 *
 * @author 80002023
 *         2017/5/13.
 * @version 1.0
 * @since 1.8
 */
@Service
public class AppVersionServiceImpl implements AppVersionService {

    @Autowired
    private AppVersionMapper appVersionMapper;


    @Override
    public AppVersion findByCode(String code) {
        if (CommonUtils.isNotEmpty(code)) {
            AppVersion t = new AppVersion();
            t.setCode(code);
            return appVersionMapper.selectOne(t);
        }
        return null;
    }

    @Override
    public int add(AppVersion record) {
        record.setCode(UUIDGenerator.generate());
        return appVersionMapper.insertSelective(record);
    }

    @Override
    public int update(AppVersion record) {
        if (CommonUtils.isNotEmpty(record) && CommonUtils.isNotEmpty(record.getId())) {
            return appVersionMapper.updateByPrimaryKeySelective(record);
        }
        return 0;
    }

    @Override
    public int updateByCode(AppVersion record) {
        if (CommonUtils.isNotEmpty(record) && CommonUtils.isNotEmpty(record.getCode())) {
            AppVersion t = this.findByCode(record.getCode());
            BeanUtils.copyProperties(record, t);
            return appVersionMapper.updateByPrimaryKeySelective(t);
        }
        return 0;
    }

    @Override
    public List<AppVersion> getList(ParamFilter paramFilter) {
        int pageNum = paramFilter.getPage().getPageNo();
        int pageSize = paramFilter.getPage().getPageSize();
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Example example = new Example(AppVersion.class);
        Map<String, Object> param = paramFilter.getParam();
        if (param != null) {
            Example.Criteria criteria = example.createCriteria();
            String name = (String) param.get("name");
            String code = (String) param.get("code");
            String status = (String) param.get("status");
            if (CommonUtils.isNotEmpty(name)) {
                criteria.andLike("name", name);
            }
            if (CommonUtils.isNotEmpty(code)) {
                criteria.andEqualTo("code", code);
            }
            if (CommonUtils.isNotEmpty(status)) {
                criteria.andEqualTo("status", status);
            }
        }
        return appVersionMapper.selectByExample(example);
    }
}
